package com.topdt.jbpm.utils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;


/**
 *  @Project       : thx-workflow
 *  @Program Name  : com.topdt.jbpm.utils.FileUtil.java
 *  @Class Name    : FileUtil
 *  @Description   : 类描述
 *  @Author        : calonlan
 *  @Creation Date : 2015年4月13日 上午10:08:15
 *  @ModificationHistory
 *  Who        When          What
 *  --------   ----------    -----------------------------------
 *  username   2015年4月13日       TODO
 */
public class FileUtil {
	public static String uploadFile( String fileName, File file,String destPath) {
		try {
			if(file==null)
				return null;
			String basePath = java.io.File.separator + "upload";
			 // 创建文件夹
	        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
	        String ymd = sdf.format(new Date());
	        String year = ymd.substring(0, 4);
			String mon = ymd.substring(4,6);
			String day = ymd.substring(6, 8);
			basePath += java.io.File.separator + year + java.io.File.separator +mon + java.io.File.separator +day ;
			java.io.File dir = new java.io.File(basePath);
			if(!dir.exists()){
				dir.mkdirs();
			}

			String newFileName = rename(fileName);
			basePath += java.io.File.separator+newFileName;
			String path = destPath + basePath;

			File destFile = new File(path);
			FileUtils.copyFile(file, destFile);

			return basePath;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static String rename(String fileName){
		Random r = new Random();
		int rannum = (int) (r.nextDouble() * (99999 - 10000 + 1)) + 10000;
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String nowTimeStr = sDateFormat.format(new Date());
		if (StringUtils.isNotBlank(fileName) && fileName.lastIndexOf(".") >= 0) {
			return nowTimeStr + rannum + "." + fileName.substring(fileName.lastIndexOf(".")+1);
		}
		return null;
	}

}
